GM = GM or gmod.GetGamemode()
if CLIENT then
	usermessage.Hook("wsbuildghost",function(msg)
		local self = gmod.GetGamemode()
		 local title = msg:ReadString()
		 if title == "false" then
			self.buildingghost = false
		 else
			self.buildingghost = title
		 end
	end)
end

local colorValid = Color(150,255,150,180)
local colorInvalid = Color(255,150,150,180)

function GM:Ghost()
	local self = gmod.GetGamemode()
	
	if not (self:IsRoundStarted() and LocalPlayer():Alive() and not LocalPlayer():WSIsPigeon()) then
		self.buildingghost = false
		return
	end
	
	if !self.buildingghost or self.buildingghost == "false" then
		self.ghostent = nil
	return end
	local title = self.buildingghost
	local item = self.items[title]
	local brotation = Angle(0, item.rotation, 0)
	local border = self.buildings[title] and self.buildings[title].ents or nil
	if not border then
		return
	end
	
	local trace = {}
	trace.start = LocalPlayer():GetShootPos()
	trace.endpos = LocalPlayer():GetShootPos() + (LocalPlayer():GetAimVector() * 250)
	trace.filter = LocalPlayer()
	local tr = util.TraceLine(trace)
	local trvalid = self:TraceValidBuild(tr, LocalPlayer())
	
	if self.ghostent then
		for k,v in ipairs(self.ghostent) do
			local off = v.dat.vec*1
			off:Rotate(brotation)
			v.ent:SetPos(tr.HitPos + off)
			v.ent:SetAngles(v.ang + brotation)
			if !trvalid then
				v.ent:SetColor(colorInvalid)
			else
				v.ent:SetColor(colorValid)
			end
		end
	else
		self.ghostent = {}
		for k,v in ipairs(border) do
			if v.ent == "ws_prop" then
				local wsent = ClientsideModel(v.mod)
				wsent:SetPos(tr.HitPos + v.vec)
				wsent:SetAngles((v.ang or Angle(0,0,0)) + brotation)
				if !trvalid then
					wsent:SetColor(colorInvalid)
				else
					wsent:SetColor(colorValid)
				end
				wsent:Spawn()
				table.insert(
					self.ghostent,
					{
						ent = wsent,
						ang = v.ang or Angle(0,0,0),
						dat = v,
					}
				)
			end
		end
	end
end

//clear;lua_run_cl gmod.GetGamemode().buildingghost = "campfire"